
import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/book_entity.dart';
import '../event/door_status_event.dart';
import '../event/index_refresh_event.dart';
import '../event/inventory_event.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/dialog_widget.dart';



class BorrowResult extends StatefulWidget {
  const BorrowResult({Key? key}) : super(key: key);

  @override
  State<BorrowResult> createState() => _BorrowResultState();
}

class _BorrowResultState extends State<BorrowResult> {

  RxList<BookEntity> borrowList = RxList();
  RxList<BookEntity> returnList = RxList();

  StreamSubscription? actionSubscription;
  StreamSubscription? lockSubscription;

  bool isDoorShow = false;


  RxList<BookEntity> bookList = RxList();


  _inventory(){
    BotToast.showLoading();
    hfSerialPortHelper.sendData(inventory());

  }

  @override
  initState() {
    super.initState();

    _inventory();
    lockSubscription = eventFactory.on<DoorStatusEvent>().listen((event) {
      if(!event.isOpen){
        _inventory();
        timer.startCountDown(CountDownMode.fast,(){
          _setResult();
        });
      }
    });

    actionSubscription = eventFactory.on<InventoryEvent>().listen((event) async {
      BotToast.closeAllLoading();
      _analysis(event.data);

    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.fast,(){
        _setResult();
      });
    });

  }

  _analysis(data) async {
    List<String> currentList = [];

    for (var item in data) {
      try{
        var id = item;
        var length = int.parse(id.substring(0,2));
        var bookNo = id.substring(2, length+2);
        currentList.add(bookNo);
      }catch(e){
        toastWarn("条码号异常");
      }
    }

    var allBook = bookQueryAll();
    var preList = allBook.where((element) => element.statue == 0).map((e) => e.no);
    List<String> returnArr = [];
    List<String> borrowArr = [];
    returnList.clear();
    borrowList.clear();

    //借出
    for (var element in preList) {
      if(!currentList.contains(element)){
        borrowArr.add(element!);
      }
    }
    //归还
    for (var element in currentList) {
      if(!preList.contains(element)){
        returnArr.add(element);
      }
    }
    // print("currentList = ${currentList.join(',')}");
    // print("preList = ${preList.join(',')}");
    // print("returnArr = ${returnArr.join(',')}");
    // print("borrowArr = ${borrowArr.join(',')}");
    for (var element in returnArr) {
      var book = bookQuery(element);
      if(book != null){
        if(book.statue == 1){
          returnList.add(book);
        }
      }else{
        var data = await findBook(element);
        if(data != null ){
          bookInsert(element, data);
          returnList.add(data);
        }
      }
    }
    for (var element in borrowArr) {
      var book = bookQuery(element);
      if(book != null){
        borrowList.add(book);
      }
    }

  }

  @override
  void dispose() {
    actionSubscription?.cancel();
    actionSubscription = null;
    lockSubscription?.cancel();
    lockSubscription  = null;
    super.dispose();
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top:10.h,left: 12.w,right: 12.w),
        width: double.infinity,
        height: 60.h,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [

            Text("借还清单",style: TextStyle(color: const Color.fromRGBO(29, 125, 168, 1),fontSize: 16.sp,fontWeight: FontWeight.bold),),
            Positioned(
                right: 0,
                child:Obx(() => Text("${timer.fastTime.value}s",style: TextStyle(color: Colors.black,fontSize: 12.sp),))
            ),
          ],
        )
    );
  }

  _confirm(){
    return InkWell(
      onTap: ()  {
        _setResult();
      },
      child:  Image.asset("assets/images/result_confirm.png", width:80.w,fit: BoxFit.fitWidth),
    );
  }

  _setResult() async {
    var showOver = false;
    BotToast.showLoading();
    for(var item in returnList){
      item.statue = 0;
      bookInsert(item.no, item);
      var res = await bookReturn(item.no);
      if(res != null){
        currentTask.offset = currentTask.offset +1;
      }
    }

    for(var item in borrowList){
      item.statue = 1;
      bookInsert(item.no, item);
      if(currentTask.offset>0){
        var res = await bookBorrow(currentTask.uid,item.no);
        if(res != null){
          currentTask.offset = currentTask.offset - 1;
        }
      }else{
        showOver = true;
        await bookBorrowCommon(settingEntity.commonUid,item.no,currentTask.uid);
      }
    }
    BotToast.closeAllLoading();

    Future.delayed(const Duration(milliseconds: 200),(){
      timer.cancel();
      currentTask.clear();
      eventFactory.fire(IndexRefreshEvent());
      DialogWidget().borrowOverDialog(showOver: showOver);
    });

  }

  _error(){
    return InkWell(
      onTap: (){
        hfSerialPortHelper.sendData(openDoor());
      },
      child: Text('信息有误？重新操作',maxLines:1,style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color: Colors.orange),),
    );
  }

  _listTitle(title){
    return Align(
      child: Text(title,style: TextStyle(color: const Color.fromRGBO(29, 125, 168, 1),fontSize: 10.sp,fontWeight: FontWeight.bold),),
    );
  }

  _listLabel(){
    return Container(
      margin: EdgeInsets.only(left: 12.w,right: 12.w,top: 8.h,bottom: 2.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _label('序号',50.w),
          _label('图书条码号',105.w),
          _label('图书名称',105.w),
          _label('操作结果',50.w),
        ],
      )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: const Color.fromRGBO(29, 125, 168, 1),fontSize: 10.sp),textAlign: TextAlign.center,),
    );
  }
  _divider(){
    return Divider(
      height: 0.5.h, // Divider 组件高度
      indent: 16.w, // 分割线左侧间距
      endIndent: 16.w, // 分割线右侧间距
      color: const Color.fromRGBO(29, 125, 168, 1),
    );
  }

  _item(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: Colors.black,fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _listItem(list,index){
    var item = list[index];
    return Container(
        padding: EdgeInsets.only(left:12.w,right:12.w,top: 2.h,bottom: 2.h),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _item('${index+1}',50.w),
            _item('${item.no}',105.w),
            _item('${item.mainTitle}',105.w),
            _item('成功',50.w),
          ],
        )
    );
  }

  _list(list){
    return Expanded(
        child: ListView.separated(
          itemBuilder: (context, index) {
            return _listItem(list,index);
          },
          itemCount: list.length,
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: 0.5.h, // Divider 组件高度
              // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
              indent: 16.w, // 分割线左侧间距
              endIndent: 16.w, // 分割线右侧间距
              color: Colors.grey,
            );
          },
        )
    );
  }

  _resultWidget(title, list){
    return Container(
      // width: 300.w,
      height: 230.h,
      decoration: const BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.fill,
          image: AssetImage(
            "assets/images/result_item_bg.png",
          ),
        ),
      ),
      margin: EdgeInsets.only(left: 20.w,right: 20.w,top: 10.h),
      padding: EdgeInsets.only(top: 18.h,bottom: 18.h),
      child: Column(
        children: [
          _listTitle(title),
          _listLabel(),
          _divider(),
          _list(list)
        ],
      ),

    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/result_bg.png",
            ),
          ),
        ),
        child: Stack(
          children: [
            _title(),
            Positioned(
              top: 40.h,
              width: 50.w,
              right: 2.w,
              child: Image.asset( "assets/images/icon1.png",width: 50.w,fit: BoxFit.fitWidth,),
            ),
            Positioned(
              top: 60.h,
              left: 0,
              right: 0,
              child: Obx(() => _resultWidget('借书清单',borrowList)),
            ),
            Positioned(
              top: 300.h,
              left: 0,
              right: 0,
              child: Obx(() => _resultWidget('还书清单',returnList)),
            ),
            Positioned(
              top: 540.h,
              left: 160.w,
              right: 160.w,
              child: _confirm(),
            ),
            Positioned(
              top: 590.h,
              left: 0,
              right: 0,
              child: Align(child:_error()),
            ),
            Positioned(
              top: 308.h,
              width: 50.w,
              left: 20.w,
              child: Image.asset( "assets/images/icon2.png",width: 50.w,fit: BoxFit.fitWidth,),
            ),

          ],
        ),
      ),
    );
  }
}

